<template>
  <el-card class="article_create">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="120px" class="demo-ruleForm">
      <el-form-item label="标题" prop="title">
        <el-input v-model="ruleForm.title" />
      </el-form-item>
      <el-form-item label="描述" prop="description">
        <el-input v-model="ruleForm.description" />
      </el-form-item>
      <el-form-item label="SEO关键字" prop="seo">
        <el-input v-model="ruleForm.seo" />
      </el-form-item>
      <el-form-item label="封面" prop="img">
        <el-upload class="avatar-uploader" :action="$upload" :data="{proof:'14e1b600b1fd579f47433b88e8d85291'}"
          :show-file-list="false" :on-success="handleUploadSuccess">
          <img v-if="ruleForm.img" style="width:100%;" :src="$cloud + ruleForm.img" class="avatar">
          <i v-else class="el-icon-plus avatar-uploader-icon" />
        </el-upload>
      </el-form-item>
      <el-form-item label="展示" prop="status">
        <el-radio-group v-model="ruleForm.status">
          <el-radio :label="1">显示</el-radio>
          <el-radio :label="0">隐藏</el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item label="标签" prop="tags">
        <el-checkbox-group v-model="ruleForm.tags">
          <el-checkbox v-for="item in tagList" :key="item.id" :label="item.id">{{item.name}}</el-checkbox>
        </el-checkbox-group>
      </el-form-item>
      <el-form-item label="排序" prop="sort">
        <el-input-number v-model="ruleForm.sort" controls-position="right" step-strictly @change="handleChange" :min="1"
          :max="10"></el-input-number>
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <mavon-editor ref="md" v-model="ruleForm.content" code-style="atom-one-dark" @imgAdd="$imgAdd"
          @imgDel="$imgDel" />
      </el-form-item>

      <el-form-item>
        <el-button @click="submitForm('ruleForm',2)" v-if="ruleForm.status == 2">保存草稿箱</el-button>
        <el-button type="primary" @click="submitForm('ruleForm',ruleForm.status)">立即更新</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
export default {
  name: 'CategoryCreate',
  data() {
    return {
      articleId: this.$route.query.id,
      tagList: [],
      mdContent: '',
      ruleForm: {
        id: this.$route.query.id,
        title: '',
        description: '',
        img: '',
        seo: '',
        status: 1,
        sort: 1,
        adminId: '',
        tags: [],
        content: '',
        md: '',
      },
      rules: {
        title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
        tags: [{ required: true, message: '请选择标签', trigger: 'blur' }],
        content: [
          { required: true, message: '请输入文章内容', trigger: 'blur' },
        ],
      },
    }
  },
  created() {
    this.initData()
  },
  methods: {
    initData() {
      this.getArticleDetail()
      this.getTagList()
    },
    // 计数器
    handleChange() { },
    // 获取文章md内容
    getMdContent(url) {
      console.log(url)

      this.$api.httpGET(this.$cloud + url).then((res) => {
        this.mdContent = res
        this.ruleForm.content = res
      })
    },
    // 获取文章详情
    getArticleDetail() {
      this.$api.httpArticleDetail(this.articleId).then((res) => {
        if (res.code == 200) {
          let article = res.data

          this.ruleForm.title = article.title
          this.ruleForm.description = article.description
          this.ruleForm.img = article.img
          this.ruleForm.seo = article.seo
          this.ruleForm.md = article.md
          this.ruleForm.status = article.status
          this.ruleForm.sort = article.sort

          // 获取标签 id
          article.tags.forEach((item) => {
            this.ruleForm.tags.push(item.id)
          })

          // 获取md原文
          this.getMdContent(article.md)
        }
      })
    },
    // 更新文章
    updateArticle() {
      // 更新文章表
      this.ruleForm.tags = JSON.stringify(this.ruleForm.tags)

      this.$api.httpArticleUpdate(this.ruleForm).then((res) => {
        if (res.code == 200) {
          // 更新md文件
          // 检测md内容是否有变化
          if (this.mdContent != this.ruleForm.content) {
            this.$api.httpPUT(this.$cloud + '/file', {
              url: this.ruleForm.md, // 文件地址 寻找文件的依据
              title: this.ruleForm.title,
              content: this.ruleForm.content,
              status: this.ruleForm.status,
            })
          }
          this.$message.success('编辑成功！')
          this.$router.push('/article/list')
        }
      })
    },
    // 上传图片成功回调
    handleUploadSuccess(res) {
      this.ruleForm.img = res.data.url
      console.log(this.ruleForm)
      this.$message.success('上传成功!')
    },
    // 编辑器删除图片回调
    $imgDel(pos, $file) {
      console.log('删除:')
      console.log(pos, $file)
    },
    // 编辑器新增上传图片回调
    $imgAdd(pos, $file) {
      console.log(pos, $file)
      // 第一步.将图片上传到服务器.
      let formdata = new FormData()
      formdata.append('file', $file)
      // :data="{proof:'14e1b600b1fd579f47433b88e8d85291'}"
      formdata.append('proof', '14e1b600b1fd579f47433b88e8d85291')
      this.$axios({
        url: this.$upload,
        method: 'post',
        data: formdata,
        headers: { 'Content-Type': 'multipart/form-data' },
      }).then((res) => {
        const json = res.data
        this.$refs.md.$img2Url(pos, this.$cloud + json.data.url)
      })
    },
    // 获取标签列表
    getTagList() {
      this.$api.httpTagList().then((res) => {
        if (res.code == 200) {
          this.tagList = res.data
        }
      })
    },
    // 提交表单
    submitForm(formName, status) {
      if (status != undefined) this.ruleForm.status = status
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.updateArticle()
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 重置表单
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
  },
}
</script>

<style lang="scss">
.article_create {
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    width: 400px;
  }

  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }

  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }
}
</style>
